<template>
  <div class="community-container">
    <h2>音乐社区</h2>
    
    <div class="posts-filter">
      <div 
        class="filter-item" 
        :class="{ active: currentSortBy === 'latest' }"
        @click="changeSortBy('latest')"
      >最新发布</div>
      <div 
        class="filter-item" 
        :class="{ active: currentSortBy === 'popular' }"
        @click="changeSortBy('popular')"
      >热门讨论</div>
      <div 
        class="filter-item" 
        :class="{ active: currentSortBy === 'followed' }"
        @click="changeSortBy('followed')"
      >我的关注</div>
      <button 
        class="new-post-btn" 
        @click="currentUser ? showNewPostModal = true : window.alert('请先登录后再发布帖子')"
      >发布新帖子</button>
    </div>
    
    <!-- 加载状态和错误消息 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>
    
    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>
    
    <div v-if="!loading && !posts.length" class="no-posts">
      <p v-if="currentSortBy === 'latest'">暂无帖子，快来发布第一篇吧！</p>
      <p v-else-if="currentSortBy === 'popular'">暂无热门帖子</p>
    </div>
    
    <div class="posts-list" v-if="posts.length > 0">
      <div v-for="post in posts" :key="post.id" class="post-item">
        <div class="post-content">
          <div class="post-header">
            <h3 class="post-title" @click="viewPostDetail(post)">{{ post.title }}</h3>
            <div class="post-meta">
              <span class="post-author">{{ post.author_name || post.author }}</span>
              <span class="post-date">{{ formatDate(post.date) }}</span>
              <button 
                v-if="currentUser && post.author_id !== currentUser.id" 
                class="follow-btn"
                :class="{ 'following': post.isFollowing }"
                @click.stop="toggleFollow(post)"
              >
                {{ post.isFollowing ? '已关注' : '关注' }}
              </button>
            </div>
          </div>
          <p class="post-text">{{ post.content }}</p>
          <div v-if="post.musicPreview" class="post-preview" @click="viewPostDetail(post)">
            <div v-if="!post.musicPreview.cover">
              <p class="debug-info">乐谱图片链接缺失，请检查数据</p>
              <p class="debug-info">visualization_url: {{post.visualization_url}}</p>
            </div>
            <img v-else :src="post.musicPreview.cover" alt="乐谱预览" class="music-preview" />
            <button class="play-btn" @click.stop="playMusic(post)" :disabled="isProcessingAudio">
              <span v-if="isPostPlaying(post.id)">暂停</span>
              <span v-else-if="isProcessingAudio && currentPlayingId === post.id">处理中...</span>
              <span v-else>播放音乐</span>
            </button>
          </div>
          <div v-else class="post-preview-placeholder">
            <span>无乐谱内容</span>
          </div>
          <div class="post-actions">
            <div class="action-item" @click="likePost(post)">
              <span class="icon-heart" :class="{ 'liked': post.liked }">
                <span v-if="post.liked">❤️</span>
                <span v-else>🖤</span>
              </span>
              <span :class="{ 'liked-text': post.liked }">{{ post.like_count || post.likes || 0 }}</span>
            </div>
            <div class="action-item" @click="viewPostDetail(post)">
              <span class="icon-comment">💬</span>
              <span>{{ post.comment_count || post.comments || 0 }}</span>
            </div>
            <div class="action-item" @click="sharePost(post)">
              <span class="icon-share">🔗</span>
              <span>分享</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 帖子详情弹窗 使用teleport -->
    <teleport to="body">
      <div v-if="showPostModal" class="post-modal">
        <div class="post-modal-content">
          <div class="post-modal-header">
            <h3>{{ currentPost.title }}</h3>
            <button @click="closeModal" class="post-modal-close">&times;</button>
          </div>
          <div class="post-modal-body">
            <div class="post-detail">
              <div class="post-author-info">
                <div class="author-name-follow">
                  <h4>{{ currentPost.author }}</h4>
                  <button 
                    v-if="currentUser && currentPost.author_id !== currentUser.id" 
                    class="follow-btn"
                    :class="{ 'following': currentPost.isFollowing }"
                    @click="toggleFollow(currentPost)"
                  >
                    {{ currentPost.isFollowing ? '已关注' : '关注' }}
                  </button>
                </div>
                <span class="post-date">{{ formatDate(currentPost.date) }}</span>
              </div>
              <div class="post-content">
                {{ currentPost.content }}
              </div>
              
              <!-- 添加点赞按钮 -->
              <div class="post-detail-actions">
                <div class="action-btn-group">
                  <button 
                    class="action-btn" 
                    :class="{'liked-btn': currentPost.liked}"
                    @click="likePost(currentPost)"
                  >
                    <span class="icon-heart" :class="{ 'liked': currentPost.liked }">
                      <span v-if="currentPost.liked">❤️</span>
                      <span v-else>🖤</span>
                    </span>
                    <span :class="{ 'liked-text': currentPost.liked }">{{ currentPost.like_count || 0 }}</span>
                  </button>
                  
                  <button 
                    class="action-btn" 
                    @click="sharePost(currentPost)"
                  >
                    <span class="icon-share">🔗</span>
                    <span>分享</span>
                  </button>
                </div>
              </div>
              
              <!-- 音乐预览 -->
              <div v-if="currentPost.musicPreview" class="music-preview-container">
                <h4><i class="fas fa-music"></i> 相关乐谱</h4>
                <div class="music-player">
                  <div class="score-image-container">
                    <img :src="currentPost.musicPreview.cover" alt="封面" class="music-cover" @click="viewLargeImage(currentPost.musicPreview.cover)" />
                    <div class="image-hint">点击查看大图</div>
                  </div>
                  <button class="play-button" @click="togglePlay()" :disabled="isProcessingAudio">
                    <i class="fas" :class="{'fa-play': !audioPlaying && !isProcessingAudio, 'fa-pause': audioPlaying, 'fa-spinner fa-pulse': isProcessingAudio}"></i>
                    <span v-if="audioPlaying">暂停</span>
                    <span v-else-if="isProcessingAudio">处理中...</span>
                    <span v-else>播放音乐</span>
                  </button>
                </div>
              </div>
              
              <!-- 评论区 -->
              <div class="comments-section" ref="commentsSection" id="comments-section">
                <h4>评论 ({{ currentPost.comments }})</h4>
                <div class="comments-list">
                  <div v-for="(comment, index) in currentPost.commentList" :key="index" class="comment">
                    <div>
                      <div class="comment-header">
                        <strong>{{ comment.author }}</strong>
                        <span class="comment-date">{{ formatDate(comment.date) }}</span>
                      </div>
                      <div class="comment-content">{{ comment.content }}</div>
                    </div>
                  </div>
                  <div v-if="currentPost.commentList.length === 0" class="no-comments">
                    暂无评论，成为第一个评论的人吧！
                  </div>
                </div>
                
                <!-- 添加评论 -->
                <div class="add-comment">
                  <div class="comment-input-container">
                    <textarea 
                      ref="commentTextarea"
                      v-model="newComment" 
                      placeholder="添加评论..." 
                      class="comment-input"
                    ></textarea>
                    <button @click="addComment" class="btn primary">发布</button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </teleport>
    
    <!-- 发布新帖子模态框 使用teleport -->
    <teleport to="body">
      <div class="new-post-modal-portal" v-if="showNewPostModal" @click.self="closeNewPostModal">
        <div class="new-post-modal-content" @click.stop>
          <span class="new-post-modal-close" @click="closeNewPostModal">&times;</span>
          <div class="new-post-modal-header">
            <h3>发布新帖子</h3>
          </div>
          <div class="new-post-form">
            <!-- 提交状态指示器 -->
            <div v-if="isSubmitting" class="upload-status">
              <div class="progress-container">
                <div class="progress-bar" :style="{width: uploadProgress + '%'}"></div>
              </div>
              <div class="progress-text">上传进度: {{ uploadProgress }}%</div>
              <div class="upload-message">正在上传并处理乐谱，请耐心等待...</div>
            </div>
            
            <div class="form-group" :class="{'disabled': isSubmitting}">
              <label for="post-title">标题</label>
              <input 
                type="text" 
                id="post-title" 
                v-model="newPost.title" 
                placeholder="请输入帖子标题（2-30字）" 
                maxlength="30"
              />
            </div>
            <div class="form-group">
              <label for="post-content">正文内容</label>
              <textarea 
                id="post-content" 
                v-model="newPost.content" 
                placeholder="请输入帖子内容（5-500字）" 
                maxlength="500"
              ></textarea>
              <div class="text-count">{{ newPost.content.length }}/500</div>
            </div>
            <div class="form-group">
              <label for="post-score">上传乐谱（可选）</label>
              <div class="score-upload-area" @click="triggerScoreUpload" :class="{'has-preview': newPost.musicPreview}">
                <input 
                  type="file" 
                  id="score-upload" 
                  ref="scoreUpload" 
                  accept="image/*" 
                  style="display: none;" 
                  @change="handleScoreUpload"
                />
                <div v-if="!newPost.musicPreview" class="upload-placeholder">
                  <span class="upload-icon">🎵</span>
                  <p>点击上传乐谱图片</p>
                  <p class="upload-hint">支持JPG、PNG格式</p>
                </div>
                <div v-else class="preview-container">
                  <img :src="newPost.musicPreview.cover" alt="乐谱预览" class="preview-image" />
                  <button class="remove-preview" @click.stop="removeScorePreview">×</button>
                </div>
              </div>
            </div>
            <div class="form-actions">
              <button @click="closeNewPostModal" class="cancel-btn" :disabled="isSubmitting">取消</button>
              <button 
                @click="submitNewPost" 
                class="submit-btn" 
                :disabled="!newPost.title.trim() || isSubmitting"
              >
                <span v-if="isSubmitting">
                  <i class="loading-spinner"></i> 
                  {{ uploadProgress > 0 ? `上传中 ${uploadProgress}%` : '处理中...' }}
                </span>
                <span v-else>发布</span>
              </button>
            </div>
            
            <!-- 上传进度条 -->
            <div v-if="isSubmitting && uploadProgress > 0" class="upload-progress-container">
              <div class="upload-progress-bar" :style="{width: uploadProgress + '%'}"></div>
            </div>
          </div>
        </div>
      </div>
    </teleport>

    <!-- 查看大图弹窗 -->
    <teleport to="body">
      <div v-if="showLargeImage" class="large-image-modal" @click="closeLargeImage">
        <div class="large-image-container">
          <img :src="largeImageSrc" alt="乐谱大图" class="large-image" />
          <button class="close-large-image" @click.stop="closeLargeImage">&times;</button>
        </div>
      </div>
    </teleport>
    
    <!-- 音频播放器 (隐藏) -->
    <audio ref="audioPlayer" @ended="onAudioEnded" @error="onAudioError" @timeupdate="updateProgress" style="display: none;"></audio>

    <!-- 添加播放控制面板 -->
    <div v-if="audioPlaying || currentPlayingId" class="audio-control-panel">
      <div class="progress-container">
        <div class="progress-bar-bg" @click="seekAudio">
          <div class="progress-bar-fill" :style="{width: `${audioProgress}%`}"></div>
        </div>
        <div class="time-display">
          <span>{{ formatTime(currentTime) }}</span>
          <span>{{ formatTime(duration) }}</span>
        </div>
      </div>
      <div class="controls">
        <button class="control-btn" @click="togglePlayGlobal">
          <i class="fas" :class="{'fa-pause': audioPlaying, 'fa-play': !audioPlaying}"></i>
        </button>
        <div class="volume-control">
          <i class="fas fa-volume-up"></i>
          <input type="range" min="0" max="1" step="0.1" v-model="volume" @input="changeVolume" />
        </div>
        <div class="speed-control">
          <span>速度:</span>
          <select v-model="playbackRate" @change="changePlaybackRate">
            <option value="0.5">0.5x</option>
            <option value="0.75">0.75x</option>
            <option value="1">1.0x</option>
            <option value="1.25">1.25x</option>
            <option value="1.5">1.5x</option>
            <option value="2">2.0x</option>
          </select>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { API_ENDPOINTS } from '../config'

export default {
  name: 'CommunityView',
  data() {
    return {
      posts: [],
      showPostModal: false,
      currentPost: null,
      newComment: '',
      audioPlaying: false,
      currentPlayingId: null,
      audioUrl: null, // 当前正在播放的音频URL
      showNewPostModal: false,
      newPost: {
        title: '',
        content: '',
        musicPreview: null
      },
      focusComment: false,
      showLargeImage: false,
      largeImageSrc: '',
      isProcessingAudio: false,
      audioProgress: 0,
      currentTime: 0,
      duration: 0,
      volume: 0.5,
      playbackRate: 1,
      currentSortBy: 'latest', // 当前排序方式：latest, popular, followed
      loading: false, // 加载状态
      errorMessage: '', // 错误信息
      currentUser: null, // 当前用户信息
      isSubmitting: false, // 是否正在提交
      uploadProgress: 0, // 上传进度
      isPostDetailLoaded: false, // 帖子详情是否已加载
      isCheckingUrl: true, // 是否正在检查URL
      isInitialCheckDone: false, // 初始URL检查是否已完成
    };
  },
  created() {
    // 初始化标志位，用于控制加载顺序
    this.isPostDetailLoaded = false;
    this.isCheckingUrl = true;
    
    // 在组件创建时获取用户信息
    this.fetchCurrentUser();
    
    // 监听哈希路由变化，以支持分享链接直接打开帖子
    window.addEventListener('hashchange', this.checkUrlForPostId);
    
    // 将强制打开帖子的方法暴露在全局对象上，方便调试
    window.forceOpenPost = (postId) => {
      console.log(`手动触发打开帖子: ID=${postId}`);
      this.loadPostFromUrl(parseInt(postId));
    };

    // 检查URL是否包含帖子ID（初始化时就检查）
    this.initialUrlCheck();
  },
  
  mounted() {
    // 先检查URL中是否有帖子ID
    this.$nextTick(() => {
      console.log('组件已挂载，准备检查URL中的帖子ID');
      // 在mounted中再次检查URL，确保登录后能正确处理带有帖子ID的URL
      this.$router.afterEach(() => {
        console.log('路由变化后检查URL中的帖子ID');
        if (!this.isPostDetailLoaded) {
          this.initialUrlCheck();
        }
      });
      
      // 不再使用async/await，而是通过Promise链避免竞态条件
      if (!this.isPostDetailLoaded && !this.isInitialCheckDone) {
        // 检查完URL后，如果没有帖子详情加载，再加载帖子列表
        setTimeout(() => {
          if (!this.isPostDetailLoaded) {
            console.log('没有检测到帖子详情，开始加载帖子列表');
            this.fetchPosts();
          }
        }, 1000); // 增加延迟确保有足够时间处理URL
      }
    });
  },
  
  beforeDestroy() {
    // 移除事件监听，避免内存泄漏
    window.removeEventListener('hashchange', this.checkUrlForPostId);
  },
  methods: {
    // 获取当前用户信息
    async fetchCurrentUser() {
      try {
        // 从本地存储获取token
        const token = localStorage.getItem('token');
        if (!token) {
          console.log('未找到用户token，用户未登录');
          this.currentUser = null;
          // 即使未登录也要获取帖子
          this.fetchPosts();
          return;
        }
        
        // 带上Authorization头发起请求
        const response = await axios.get(API_ENDPOINTS.USER_PROFILE, {
          headers: {
            'Authorization': `Bearer ${token}`
          },
          withCredentials: false // 设置为false避免CORS问题
        });
        
        this.currentUser = response.data;
        console.log('用户信息获取成功:', this.currentUser);
        console.log('用户ID类型:', typeof this.currentUser.id);
        
        // 获取用户信息后立即获取帖子
        this.fetchPosts();
      } catch (error) {
        console.error('获取用户信息失败:', error);
        // 用户未登录或获取信息失败，设置为null
        this.currentUser = null;
        
        // 即使获取用户信息失败也要获取帖子
        this.fetchPosts();
        
        // 如果是401错误，可能是token失效，尝试清除token
        if (error.response && error.response.status === 401) {
          localStorage.removeItem('token');
        }
      }
    },
    
    // 获取帖子列表
    async fetchPosts(sortBy = this.currentSortBy) {
      this.loading = true;
      this.errorMessage = '';
      this.currentSortBy = sortBy;
      
      try {
        // 构建API请求参数
        const params = {
          sort_by: sortBy,
          limit: 20,
          offset: 0,
        };
        
        // 如果用户已登录，添加user_id参数
        if (this.currentUser) {
          params.user_id = this.currentUser.id;
          console.log('用户已登录，添加user_id参数:', this.currentUser.id, '类型:', typeof this.currentUser.id);
        } else {
          console.log('用户未登录，不添加user_id参数');
        }
        
        console.log('获取帖子列表:', params);
        
        const response = await axios.get(API_ENDPOINTS.COMMUNITY_POSTS, { params });
        this.posts = response.data;
        
        // 打印第一个帖子的信息，用于调试
        if (this.posts.length > 0) {
          const firstPost = this.posts[0];
          console.log('第一个帖子信息:', {
            id: firstPost.id,
            title: firstPost.title,
            visualization_url: firstPost.visualization_url,
            score_upload_id: firstPost.score_upload_id,
            musicPreview: firstPost.musicPreview
          });
        }
        
        // 确保所有帖子的liked属性是布尔值
        this.posts.forEach(post => {
          console.log(`获取到原始帖子数据 - ID: ${post.id}, 原始点赞状态: ${post.liked}, 类型: ${typeof post.liked}`);
          // 将数字0/1或字符串"0"/"1"转换为布尔值
          if (typeof post.liked !== 'boolean') {
            post.liked = Boolean(post.liked) && post.liked !== '0';
          }
          
          // 确保时间戳是JavaScript Date对象可以识别的格式
          if (post.date) {
            console.log(`帖子日期原始值: ${post.date}`);
          }
        });
        
        // 获取帖子列表后，检查关注状态
        if (this.currentUser) {
          this.checkFollowStatus();
        }
      } catch (error) {
        console.error('获取帖子列表失败:', error);
        this.errorMessage = '获取帖子列表失败，请稍后重试';
      } finally {
        this.loading = false;
      }
    },
    
    // 检查关注状态
    async checkFollowStatus() {
      if (!this.currentUser) return;
      
      // 对于每个帖子，检查是否关注了作者
      const authorIds = [...new Set(this.posts.map(post => post.author_id))];
      
      for (const authorId of authorIds) {
        if (authorId === this.currentUser.id) continue; // 跳过自己
        
        try {
          const response = await axios.get(API_ENDPOINTS.CHECK_FOLLOW_STATUS(authorId), {
            params: { follower_id: this.currentUser.id }
          });
          
          // 更新所有该作者的帖子的关注状态
          this.posts.forEach(post => {
            if (post.author_id === authorId) {
              post.isFollowing = response.data.following;
            }
          });
        } catch (error) {
          console.error(`检查关注状态失败 (作者 ID: ${authorId}):`, error);
        }
      }
    },
    
    // 关注/取消关注
    async toggleFollow(post) {
      if (!this.currentUser) {
        window.alert('请先登录后再关注');
        return;
      }
      
      const authorId = post.author_id;
      if (authorId === this.currentUser.id) {
        window.alert('不能关注自己');
        return;
      }
      
      try {
        const formData = new FormData();
        formData.append('follower_id', this.currentUser.id);
        
        if (post.isFollowing) {
          // 取消关注
          await axios.post(API_ENDPOINTS.UNFOLLOW_USER(authorId), formData);
          // 更新所有该作者的帖子的关注状态
          this.posts.forEach(p => {
            if (p.author_id === authorId) {
              p.isFollowing = false;
            }
          });
          
          // 如果当前是关注帖子列表且正在取消关注，需要刷新列表
          if (this.currentSortBy === 'followed') {
            this.fetchFollowedPosts();
          }
        } else {
          // 关注
          await axios.post(API_ENDPOINTS.FOLLOW_USER(authorId), formData);
          // 更新所有该作者的帖子的关注状态
          this.posts.forEach(p => {
            if (p.author_id === authorId) {
              p.isFollowing = true;
            }
          });
        }
      } catch (error) {
        console.error('关注/取消关注操作失败:', error);
        window.alert('操作失败，请稍后重试');
      }
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      
      // 检查日期是否有效
      if (isNaN(date.getTime())) {
        console.error('无效的日期字符串:', dateString);
        return '日期无效';
      }

      // 检查字符串格式，判断是否包含时间部分
      if (dateString.includes(':') || dateString.length > 10) {
        // 完整格式，显示年月日时分
        return date.toLocaleDateString('zh-CN', { 
          year: 'numeric', 
          month: 'long', 
          day: 'numeric',
          hour: '2-digit',
          minute: '2-digit'
        });
      } else {
        // 只有日期部分，只显示年月日
        return date.toLocaleDateString('zh-CN', { 
          year: 'numeric', 
          month: 'long', 
          day: 'numeric' 
        });
      }
    },
    
    // 查看帖子详情
    async viewPostDetail(post) {
      this.loading = true;
      this.errorMessage = '';
      
      try {
        // 构建API请求参数
        const params = {};
        if (this.currentUser) {
          params.user_id = this.currentUser.id;
        }
        
        console.log('获取帖子详情:', {
          postId: post.id, 
          userId: this.currentUser ? this.currentUser.id : null
        });
        
        const response = await axios.get(API_ENDPOINTS.COMMUNITY_POST_DETAIL(post.id), { params });
        this.currentPost = response.data;
        
        // 额外获取点赞状态，确保点赞信息是最新的
        if (this.currentUser) {
          try {
            console.log(`单独获取点赞状态: postId=${post.id}, userId=${this.currentUser.id}`);
            const likeStatusResponse = await axios.get(
              API_ENDPOINTS.COMMUNITY_POST_LIKE_STATUS(post.id), 
              { params: { user_id: this.currentUser.id } }
            );
            console.log('获取到的点赞状态:', likeStatusResponse.data);
            
            // 更新点赞状态
            if (likeStatusResponse.data) {
              this.currentPost.liked = likeStatusResponse.data.liked;
              this.currentPost.like_count = likeStatusResponse.data.like_count;
              console.log(`更新后的点赞状态: ${this.currentPost.liked}, 点赞数: ${this.currentPost.like_count}`);
            }
          } catch (likeError) {
            console.error('获取点赞状态失败:', likeError);
          }
        }
        
        this.newComment = '';
        this.showPostModal = true;
        this.focusComment = false;
        
        // 如果用户已登录，检查是否关注了作者
        if (this.currentUser && this.currentPost.author_id !== this.currentUser.id) {
          try {
            const followResponse = await axios.get(API_ENDPOINTS.CHECK_FOLLOW_STATUS(this.currentPost.author_id), {
              params: { follower_id: this.currentUser.id }
            });
            this.currentPost.isFollowing = followResponse.data.following;
          } catch (error) {
            console.error('检查关注状态失败:', error);
          }
        }
        
        // 重置滚动位置，总是从顶部开始显示
        this.$nextTick(() => {
          const modalBody = document.querySelector('.post-modal-body');
          if (modalBody) {
            modalBody.scrollTop = 0;
          }
        });
      } catch (error) {
        console.error('获取帖子详情失败:', error);
        this.errorMessage = '获取帖子详情失败，请稍后重试';
      } finally {
        this.loading = false;
      }
    },
    
    // 关闭帖子详情模态框
    closeModal() {
      this.showPostModal = false;
      this.currentPost = null;
      this.newComment = '';
      this.focusComment = false;
      
      // 如果正在播放音频，停止播放
      if (this.audioPlaying) {
        this.stopAudio();
      }
    },
    
    // 切换音频播放状态
    togglePlay() {
      if (this.currentPost) {
        if (this.audioPlaying) {
          // 如果正在播放，则暂停
          const audioPlayer = this.$refs.audioPlayer;
          if (audioPlayer) {
            audioPlayer.pause();
            this.audioPlaying = false;
          }
        } else {
          // 如果已暂停，则继续播放
          if (this.currentPlayingId && this.$refs.audioPlayer && this.$refs.audioPlayer.src) {
            // 如果已经有音频加载，就直接播放
            this.$refs.audioPlayer.play()
              .then(() => {
                this.audioPlaying = true;
              })
              .catch(error => {
                console.error('恢复播放失败:', error);
                alert('播放失败，请重试');
              });
          } else {
            // 否则从头开始加载并播放
            this.playMusic(this.currentPost);
          }
        }
      }
    },
    
    // 增加一个全局播放/暂停切换方法，不依赖于当前帖子
    togglePlayGlobal() {
      if (this.audioPlaying) {
        // 如果正在播放，则暂停
        const audioPlayer = this.$refs.audioPlayer;
        if (audioPlayer) {
          audioPlayer.pause();
          this.audioPlaying = false;
        }
      } else {
        // 如果已暂停，则继续播放
        if (this.currentPlayingId && this.$refs.audioPlayer && this.$refs.audioPlayer.src) {
          this.$refs.audioPlayer.play()
            .then(() => {
              this.audioPlaying = true;
            })
            .catch(error => {
              console.error('恢复播放失败:', error);
              alert('播放失败，请重试');
            });
        }
      }
    },
    
    // 播放音乐
    async playMusic(post) {
      // 如果点击的是正在播放的帖子，则暂停播放
      if (this.currentPlayingId === post.id && this.audioPlaying) {
        const audioPlayer = this.$refs.audioPlayer;
        if (audioPlayer) {
          audioPlayer.pause();
          this.audioPlaying = false;
        }
        return;
      }
      
      // 如果点击的是已加载但暂停的帖子，则继续播放
      if (this.currentPlayingId === post.id && !this.audioPlaying && this.$refs.audioPlayer && this.$refs.audioPlayer.src) {
        this.$refs.audioPlayer.play()
          .then(() => {
            this.audioPlaying = true;
          })
          .catch(error => {
            console.error('恢复播放失败:', error);
            alert('播放失败，请重试');
          });
        return;
      }
      
      // 如果是播放新帖子，先停止当前的播放
      if (this.audioPlaying) {
        this.stopAudio();
      }
      
      // 开始处理新音频
      this.isProcessingAudio = true;
      this.currentPlayingId = post.id; // 立即设置当前播放ID，避免用户重复点击
      
      try {
        // 如果这个帖子已经有缓存的音频URL，直接使用
        if (post.musicPreview && post.musicPreview.audioUrl) {
          this.startPlayingAudio(post.musicPreview.audioUrl, post.id);
          return;
        }
        
        // 检查是否有score_upload_id
        if (!post.score_upload_id) {
          throw new Error('该帖子没有关联乐谱');
        }
        
        // 请求获取音频URL
        const response = await axios.get(API_ENDPOINTS.COMMUNITY_AUDIO(post.score_upload_id));
        
        if (response.data && response.data.audio_url) {
          // 缓存到帖子中
          if (!post.musicPreview) {
            post.musicPreview = {
              title: post.score_title || '未命名乐谱',
              cover: post.visualization_url || '',
              audioUrl: response.data.audio_url
            };
          } else {
            post.musicPreview.audioUrl = response.data.audio_url;
          }
          
          this.startPlayingAudio(response.data.audio_url, post.id);
        } else {
          throw new Error('获取音频URL失败');
        }
      } catch (error) {
        console.error('获取或播放音频失败:', error);
        this.isProcessingAudio = false;
        this.currentPlayingId = null; // 重置当前播放ID
        alert('音频播放失败: ' + (error.message || '请重试'));
      }
    },
    
    // 音频播放相关函数
    startPlayingAudio(audioUrl, postId) {
      this.audioUrl = audioUrl;
      this.currentPlayingId = postId;
      this.isProcessingAudio = false;
      
      // 设置音频源并播放
      this.$nextTick(() => {
        const audioPlayer = this.$refs.audioPlayer;
        if (audioPlayer) {
          audioPlayer.src = audioUrl;
          audioPlayer.volume = this.volume;
          audioPlayer.playbackRate = this.playbackRate;
          audioPlayer.load();
          audioPlayer.play()
            .then(() => {
              this.audioPlaying = true;
            })
            .catch(error => {
              console.error('播放音频失败:', error);
              this.stopAudio();
              window.alert('播放失败，请重试');
            });
        }
      });
    },
    
    // 停止播放音频
    stopAudio() {
      const audioPlayer = this.$refs.audioPlayer;
      if (audioPlayer) {
        audioPlayer.pause();
        audioPlayer.currentTime = 0;
      }
      
      this.audioPlaying = false;
      this.currentPlayingId = null;
    },
    
    // 音频播放结束事件处理
    onAudioEnded() {
      this.stopAudio();
    },
    
    // 音频错误事件处理
    onAudioError(event) {
      console.error('音频播放错误:', event);
      this.stopAudio();
      window.alert('音频播放遇到错误，请重试');
    },
    
    // 添加评论
    async addComment() {
      if (!this.newComment.trim()) return;
      
      if (!this.currentUser) {
        window.alert('请先登录后再评论');
        return;
      }
      
      // 检查是否在评论冷却时间内
      const lastCommentTime = localStorage.getItem('last_comment_time');
      const now = Date.now();
      if (lastCommentTime && (now - parseInt(lastCommentTime)) < 10000) { // 10秒内只能评论一次
        window.alert('评论过于频繁，请10秒后再试');
        return;
      }
      
      try {
        // 先更新UI，提高响应速度
        const currentCommentCount = this.currentPost.comments || 0;
        this.currentPost.comments = currentCommentCount + 1; // 立即更新评论数
        
        // 更新原始帖子列表中的评论计数
        const originalPost = this.posts.find(p => p.id === this.currentPost.id);
        if (originalPost) {
          originalPost.comment_count = (originalPost.comment_count || 0) + 1;
          originalPost.comments = this.currentPost.comments;
        }
        
        // 准备评论数据
        const formData = new FormData();
        formData.append('content', this.newComment);
        formData.append('user_id', this.currentUser.id);
        
        // 记录评论时间，实现冷却功能
        localStorage.setItem('last_comment_time', now.toString());
        
        const response = await axios.post(
          API_ENDPOINTS.COMMUNITY_POST_COMMENTS(this.currentPost.id), 
          formData
        );
        
        // 添加到当前帖子的评论列表顶部（而不是推到末尾）
        this.currentPost.commentList.unshift(response.data);
        this.currentPost.comment_count = this.currentPost.commentList.length;
        
        // 清空评论框
        this.newComment = '';
      } catch (error) {
        console.error('添加评论失败:', error);
        window.alert('添加评论失败，请稍后重试');
        
        // 恢复原来的评论数
        if (this.currentPost) {
          this.currentPost.comments = (this.currentPost.comments || 1) - 1;
        }
        
        // 恢复原始帖子列表中的评论计数
        const originalPost = this.posts.find(p => p.id === this.currentPost.id);
        if (originalPost) {
          originalPost.comment_count = (originalPost.comment_count || 1) - 1;
          originalPost.comments = this.currentPost.comments;
        }
      }
    },
    
    // 点赞帖子
    async likePost(post) {
      if (!this.currentUser) {
        window.alert('请先登录后再点赞');
        return;
      }
      
      // 检查是否正在处理该帖子的点赞请求
      const likeProcessingKey = `like_processing_${post.id}`;
      if (this[likeProcessingKey]) {
        return; // 防止重复点击
      }
      
      // 设置处理标志
      this[likeProcessingKey] = true;
      
      // 记录当前点赞按钮元素
      const heartIcon = event.currentTarget.querySelector('.icon-heart');
      
      // 乐观更新UI
      const originalLikeStatus = Boolean(post.liked);
      const originalLikeCount = post.like_count || 0;
      
      console.log('点赞前状态:', {
        id: post.id,
        originalStatus: originalLikeStatus,
        originalCount: originalLikeCount,
        likedType: typeof post.liked
      });
      
      // 先在界面上更新状态，让用户立即看到反馈
      post.liked = !originalLikeStatus;
      post.like_count = originalLikeStatus 
        ? Math.max(0, originalLikeCount - 1) 
        : originalLikeCount + 1;
      
      // 如果是点赞操作，添加动画类
      if (post.liked && heartIcon) {
        heartIcon.classList.remove('heartPulse');
        // 触发重排
        void heartIcon.offsetWidth;
        heartIcon.classList.add('heartPulse');
      }
      
      try {
        const formData = new FormData();
        formData.append('user_id', this.currentUser.id);
        
        console.log('发送点赞请求:', {
          postId: post.id,
          userId: this.currentUser.id,
          api: API_ENDPOINTS.COMMUNITY_POST_LIKE(post.id)
        });
        
        const response = await axios.post(
          API_ENDPOINTS.COMMUNITY_POST_LIKE(post.id), 
          formData
        );
        
        console.log('服务器返回点赞状态:', response.data);
        
        // 使用服务器返回的实际状态更新
        post.liked = Boolean(response.data.liked);
        post.like_count = response.data.like_count;
        
        console.log('更新后点赞状态:', {
          id: post.id,
          liked: post.liked,
          likedType: typeof post.liked,
          likeCount: post.like_count
        });
        
        // 如果当前正在查看的帖子是被点赞的帖子，也更新它的状态
        if (this.currentPost && this.currentPost.id === post.id) {
          this.currentPost.liked = Boolean(response.data.liked);
          this.currentPost.like_count = response.data.like_count;
        }
        
        // 同步更新列表中所有相同ID的帖子
        if (this.posts && this.posts.length > 0) {
          this.posts.forEach(p => {
            if (p.id === post.id) {
              p.liked = Boolean(response.data.liked);
              p.like_count = response.data.like_count;
            }
          });
        }
      } catch (error) {
        console.error('点赞操作失败:', error);
        console.error('错误详情:', error.response ? error.response.data : '无响应数据');
        
        // 操作失败时恢复原始状态
        post.liked = originalLikeStatus;
        post.like_count = originalLikeCount;
        
        // 检查是否为频率限制错误
        if (error.response && error.response.status === 429) {
          let retryAfter = 5; // 默认5秒
          if (error.response.data && error.response.data.retry_after) {
            retryAfter = error.response.data.retry_after;
          }
          window.alert(`操作过于频繁，请${retryAfter}秒后再试`);
        } else if (error.response && error.response.status === 401) {
          window.alert('登录已过期，请重新登录');
          localStorage.removeItem('token');
          this.currentUser = null;
        } else if (error.response && error.response.status === 500) {
          // 如果是服务器错误，尝试重新获取点赞状态
          try {
            const statusResponse = await axios.get(
              API_ENDPOINTS.COMMUNITY_POST_LIKE_STATUS(post.id),
              { params: { user_id: this.currentUser.id } }
            );
            if (statusResponse.data) {
              post.liked = Boolean(statusResponse.data.liked);
              post.like_count = statusResponse.data.like_count;
              
              // 同步到当前查看的帖子
              if (this.currentPost && this.currentPost.id === post.id) {
                this.currentPost.liked = post.liked;
                this.currentPost.like_count = post.like_count;
              }
            }
          } catch (statusError) {
            console.error('获取点赞状态失败:', statusError);
          }
        } else {
          window.alert('点赞操作失败，请稍后重试');
        }
      } finally {
        // 延迟一段时间后清除处理标志，防止用户快速重复点击
        setTimeout(() => {
          this[likeProcessingKey] = false;
        }, 1000);
      }
    },
    
    // 重置表单
    resetPostForm() {
      this.newPost = {
        title: '',
        content: '',
        musicPreview: null
      };
      
      // 重置文件输入
      if (this.$refs.scoreUpload) {
        this.$refs.scoreUpload.value = null;
      }
    },
    
    // 查看大图
    viewLargeImage(src) {
      this.largeImageSrc = src;
      this.showLargeImage = true;
    },
    
    // 关闭大图
    closeLargeImage() {
      this.showLargeImage = false;
    },
    
    // 检查帖子是否正在播放
    isPostPlaying(postId) {
      return this.currentPlayingId === postId && this.audioPlaying;
    },
    
    // 更新播放进度
    updateProgress(event) {
      const audio = event.target;
      this.currentTime = audio.currentTime;
      this.duration = audio.duration;
      this.audioProgress = (this.currentTime / this.duration) * 100 || 0;
    },
    
    // 格式化时间
    formatTime(seconds) {
      if (isNaN(seconds) || !isFinite(seconds)) return '0:00';
      const mins = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${mins}:${secs < 10 ? '0' + secs : secs}`;
    },
    
    // 改变音量
    changeVolume() {
      if (this.$refs.audioPlayer) {
        this.$refs.audioPlayer.volume = this.volume;
      }
    },
    
    // 改变播放速度
    changePlaybackRate() {
      if (this.$refs.audioPlayer) {
        this.$refs.audioPlayer.playbackRate = this.playbackRate;
      }
    },
    
    // 跳转播放进度
    seekAudio(event) {
      const audio = this.$refs.audioPlayer;
      if (audio) {
        const progressBar = event.currentTarget;
        const clickPosition = event.offsetX;
        const barWidth = progressBar.clientWidth;
        const seekPercentage = (clickPosition / barWidth) * 100;
        this.audioProgress = seekPercentage;
        audio.currentTime = (seekPercentage / 100) * this.duration;
      }
    },
    
    // 切换排序方式
    changeSortBy(sortBy) {
      if (sortBy === 'followed' && !this.currentUser) {
        window.alert('请先登录后再查看关注内容');
        return;
      }
      
      if (this.currentSortBy !== sortBy) {
        if (sortBy === 'followed') {
          this.fetchFollowedPosts();
        } else {
          this.fetchPosts(sortBy);
        }
      }
    },
    
    // 获取关注的人发布的帖子
    async fetchFollowedPosts() {
      if (!this.currentUser) {
        window.alert('请先登录后再查看关注内容');
        return;
      }
      
      this.loading = true;
      this.errorMessage = '';
      this.currentSortBy = 'followed';
      
      try {
        // 构建API请求参数
        const params = {
          user_id: this.currentUser.id,
          followed_only: true, // 添加一个参数，表示只获取关注的人的帖子
          sort_by: 'mixed',    // 时间和热度综合排序
          limit: 20,
          offset: 0
        };
        
        console.log('获取关注的人的帖子:', params);
        
        const response = await axios.get(API_ENDPOINTS.COMMUNITY_POSTS, { params });
        this.posts = response.data;
        
        if (this.posts.length === 0) {
          this.errorMessage = '你还没有关注任何人，或关注的人还没有发布帖子。去发现更多有趣的人吧！';
        }
        
        // 确保所有帖子的liked属性是布尔值
        this.posts.forEach(post => {
          if (typeof post.liked !== 'boolean') {
            post.liked = Boolean(post.liked) && post.liked !== '0';
          }
        });
        
        // 获取帖子列表后，确保显示正确的关注状态
        this.checkFollowStatus();
      } catch (error) {
        console.error('获取关注的人的帖子失败:', error);
        this.errorMessage = '获取关注内容失败，请稍后重试';
      } finally {
        this.loading = false;
      }
    },
    
    // 关闭新帖子模态框
    closeNewPostModal() {
      this.showNewPostModal = false;
      this.resetNewPostForm();
    },
    
    // 重置新帖子表单
    resetNewPostForm() {
      this.newPost = {
        title: '',
        content: '',
        musicPreview: null
      };
      
      // 重置文件输入
      if (this.$refs.scoreUpload) {
        this.$refs.scoreUpload.value = null;
      }
    },
    
    // 触发乐谱上传
    triggerScoreUpload() {
      if (!this.newPost.musicPreview && this.$refs.scoreUpload) {
        this.$refs.scoreUpload.click();
      }
    },
    
    // 处理乐谱上传
    handleScoreUpload(event) {
      const file = event.target.files[0];
      if (file) {
        // 创建临时预览
        const previewUrl = URL.createObjectURL(file);
        this.newPost.musicPreview = {
          title: this.newPost.title || '新乐谱',
          cover: previewUrl,
          file: file  // 存储文件对象，用于后续上传
        };
      }
    },
    
    // 移除乐谱预览
    removeScorePreview(event) {
      event.preventDefault();
      
      // 如果有预览URL，释放它
      if (this.newPost.musicPreview && this.newPost.musicPreview.cover) {
        URL.revokeObjectURL(this.newPost.musicPreview.cover);
      }
      
      this.newPost.musicPreview = null;
      
      // 重置文件输入
      if (this.$refs.scoreUpload) {
        this.$refs.scoreUpload.value = null;
      }
    },
    
    // 提交新帖子
    async submitNewPost() {
      // 检查表单
      if (!this.newPost.title.trim()) {
        window.alert('标题不能为空');
        return;
      }
      
      if (!this.currentUser) {
        window.alert('请先登录后再发布帖子');
        return;
      }
      
      // 设置提交状态
      this.isSubmitting = true;
      this.uploadProgress = 0;
      
      try {
        const formData = new FormData();
        formData.append('title', this.newPost.title);
        formData.append('content', this.newPost.content);
        formData.append('user_id', this.currentUser.id);
        
        // 如果有乐谱文件，添加到formData
        if (this.newPost.musicPreview && this.newPost.musicPreview.file) {
          formData.append('score_file', this.newPost.musicPreview.file);
        }
        
        // 获取用户token
        const token = localStorage.getItem('token');
        if (!token) {
          alert('登录状态已过期，请重新登录');
          this.isSubmitting = false;
          return;
        }
        
        // 使用API_ENDPOINTS中定义的路径
        const response = await axios.post(
          API_ENDPOINTS.COMMUNITY_POSTS.replace('posts-list', 'post-create'), 
          formData, 
          {
            headers: {
              'Authorization': `Bearer ${token}`,
              'Content-Type': 'multipart/form-data'
            },
            // 添加上传进度监听
            onUploadProgress: (progressEvent) => {
              if (progressEvent.total) {
                this.uploadProgress = Math.round((progressEvent.loaded * 100) / progressEvent.total);
                console.log(`上传进度: ${this.uploadProgress}%`);
              }
            },
            // 添加超时设置
            timeout: 120000 // 2分钟超时，乐谱处理可能需要较长时间
          }
        );
        
        // 关闭模态框，但保持加载状态显示
        this.showNewPostModal = false;
        
        // 上传完成后，清理资源并更新UI
        console.log('帖子发布成功:', response.data);
        
        // 重置表单
        this.resetPostForm();
        
        // 刷新帖子列表
        this.fetchPosts(this.currentSortBy);
        
        // 显示成功消息
        setTimeout(() => {
          alert('帖子发布成功！');
        }, 500);
      } catch (error) {
        console.error('发布帖子失败:', error);
        this.isSubmitting = false;
        
        let errorMsg = '发布失败，请稍后重试';
        
        if (error.response && error.response.status === 401) {
          errorMsg = '登录状态已过期，请重新登录';
          localStorage.removeItem('token');
          this.currentUser = null;
        } else if (error.response && error.response.data && error.response.data.detail) {
          errorMsg = error.response.data.detail;
        }
        
        window.alert(errorMsg);
      } finally {
        // 完成后重置状态
        this.isSubmitting = false;
        this.uploadProgress = 0;
      }
    },
    
    // 播放音频
    async playPostAudio(post) {
      if (this.isProcessingAudio) return;
      
      // 如果已经有音频在播放，先停止它
      if (this.audioPlaying) {
        this.stopAudio();
      }
      
      // 如果是同一个帖子，仅切换播放状态
      if (this.currentPlayingId === post.id) {
        const audioPlayer = this.$refs.audioPlayer;
        if (audioPlayer) {
          audioPlayer.play()
            .then(() => {
              this.audioPlaying = true;
            })
            .catch(error => {
              console.error('播放音频失败:', error);
              window.alert('播放失败，请重试');
            });
        }
        return;
      }
      
      this.isProcessingAudio = true;
      this.currentPlayingId = post.id;
      
      try {
        // 如果音乐预览中已经有音频URL，直接播放
        if (post.musicPreview && post.musicPreview.audioUrl) {
          this.startPlayingAudio(post.musicPreview.audioUrl, post.id);
        } else if (post.score_upload_id) {
          // 否则，获取音频URL
          const response = await axios.get(API_ENDPOINTS.COMMUNITY_POST_AUDIO(post.score_upload_id));
          
          if (response.data && response.data.audio_url) {
            // 更新音乐预览对象
            if (!post.musicPreview) {
              post.musicPreview = {
                title: post.score_title || '未命名乐谱',
                cover: post.visualization_url || '',
                audioUrl: response.data.audio_url
              };
            } else {
              post.musicPreview.audioUrl = response.data.audio_url;
            }
            
            this.startPlayingAudio(response.data.audio_url, post.id);
          } else {
            throw new Error('获取音频URL失败');
          }
        } else {
          throw new Error('获取音频URL失败');
        }
      } catch (error) {
        console.error('获取或播放音频失败:', error);
        this.isProcessingAudio = false;
        this.currentPlayingId = null; // 重置当前播放ID
        window.alert('音频播放失败: ' + (error.message || '请重试'));
      }
    },
    
    // 分享帖子（复制链接到剪贴板）
    sharePost(post) {
      // 构建帖子详情页的URL，使用当前网站的路由格式
      let baseUrl = window.location.href;
      // 移除已有的hash部分（如果有）
      if (baseUrl.includes('#')) {
        baseUrl = baseUrl.split('#')[0];
      }
      // 确保baseUrl以/结尾
      if (!baseUrl.endsWith('/')) {
        baseUrl += '/';
      }
      
      const postUrl = `${baseUrl}#/community/post/${post.id}`;
      console.log('生成的分享链接:', postUrl);
      
      // 使用 Clipboard API 复制到剪贴板
      navigator.clipboard.writeText(postUrl)
        .then(() => {
          // 显示成功提示
          alert('帖子链接已复制到剪贴板');
        })
        .catch(err => {
          // 复制失败时的处理
          console.error('复制到剪贴板失败:', err);
          // 提供备选方案
          alert(`复制失败，请手动复制: ${postUrl}`);
        });
      
      // 阻止事件冒泡，避免触发帖子详情查看
      event.stopPropagation();
    },
    
    // 检查URL中是否包含帖子ID (用于hash变化时调用)
    async checkUrlForPostId() {
      // 解析URL哈希值和完整路径
      const hash = window.location.hash;
      const fullUrl = window.location.href;
      
      console.log('哈希变化 - 当前URL:', fullUrl);
      console.log('哈希变化 - 当前哈希值:', hash);
      
      // 尝试多种可能的URL格式匹配
      
      // 1. 匹配形如 #/community/post/123 的哈希路径
      let match = hash.match(/#\/community\/post\/(\d+)/);
      
      // 2. 如果上面没匹配到，尝试匹配 /community/post/123
      if (!match) {
        match = fullUrl.match(/\/community\/post\/(\d+)/);
      }
      
      // 3. 专门匹配 http://localhost:8080/community#/community/post/8 这种格式
      if (!match && fullUrl.includes('/community#/community/post/')) {
        match = fullUrl.match(/\/community#\/community\/post\/(\d+)/);
      }
      
      // 4. 最后尝试提取URL中任何位置的数字作为帖子ID
      if (!match && hash.includes('post/')) {
        match = hash.match(/post\/(\d+)/);
      }
      
      if (match && match[1]) {
        const postId = parseInt(match[1]);
        console.log(`哈希变化 - 检测到URL中包含帖子ID: ${postId}，准备加载帖子详情`);
        
        this.isPostDetailLoaded = true; // 标记正在加载帖子详情
        
        // 立即加载帖子详情，不再使用setTimeout延迟
        console.log(`哈希变化 - 立即加载帖子ID: ${postId}`);
        await this.loadPostFromUrl(postId);
        return true; // 返回true表示找到了帖子ID
      } else {
        console.log('哈希变化 - 未在URL中检测到帖子ID');
        this.isPostDetailLoaded = false; // 没有找到帖子ID
        return false; // 返回false表示没找到帖子ID
      }
    },
    
    // 根据ID加载帖子并显示详情
    async loadPostFromUrl(postId) {
      // 如果已经在加载中，不重复操作
      if (this.loading) return;
      
      this.loading = true;
      console.log(`开始加载ID为${postId}的帖子详情`);
      
      try {
        // 构建API请求参数
        const params = {};
        if (this.currentUser) {
          params.user_id = this.currentUser.id;
        }
        
        console.log(`发送API请求获取帖子详情: postId=${postId}, params=`, params);
        
        // 请求帖子详情
        const response = await axios.get(API_ENDPOINTS.COMMUNITY_POST_DETAIL(postId), { params });
        console.log('获取到的帖子详情数据:', response.data);
        
        // 设置当前帖子
        this.currentPost = response.data;
        
        // 额外获取点赞状态，确保点赞信息是最新的
        if (this.currentUser) {
          try {
            console.log(`单独获取点赞状态: postId=${postId}, userId=${this.currentUser.id}`);
            const likeStatusResponse = await axios.get(
              API_ENDPOINTS.COMMUNITY_POST_LIKE_STATUS(postId), 
              { params: { user_id: this.currentUser.id } }
            );
            console.log('获取到的点赞状态:', likeStatusResponse.data);
            
            // 更新点赞状态
            if (likeStatusResponse.data) {
              this.currentPost.liked = likeStatusResponse.data.liked;
              this.currentPost.like_count = likeStatusResponse.data.like_count;
              console.log(`更新后的点赞状态: ${this.currentPost.liked}, 点赞数: ${this.currentPost.like_count}`);
            }
          } catch (likeError) {
            console.error('获取点赞状态失败:', likeError);
          }
        }
        
        this.newComment = '';
        this.showPostModal = true;
        this.focusComment = false;
        
        // 如果用户已登录，检查是否关注了作者
        if (this.currentUser && this.currentPost.author_id !== this.currentUser.id) {
          try {
            const followResponse = await axios.get(API_ENDPOINTS.CHECK_FOLLOW_STATUS(this.currentPost.author_id), {
              params: { follower_id: this.currentUser.id }
            });
            this.currentPost.isFollowing = followResponse.data.following;
          } catch (error) {
            console.error('检查关注状态失败:', error);
          }
        }
        
        // 重置滚动位置，总是从顶部开始显示
        this.$nextTick(() => {
          const modalBody = document.querySelector('.post-modal-body');
          if (modalBody) {
            modalBody.scrollTop = 0;
          }
        });
      } catch (error) {
        console.error('获取帖子详情失败:', error);
        this.errorMessage = '获取帖子详情失败，请稍后重试';
      } finally {
        this.loading = false;
      }
    },
    
    // 使用可靠的方式显示模态框，带重试机制
    showModalWithRetry(retryCount = 0) {
      console.log(`尝试显示模态框，第${retryCount + 1}次尝试`);
      
      // 先确保模态框状态是打开的
      this.showPostModal = true;
      
      // 在下一个渲染周期检查模态框DOM是否存在
      this.$nextTick(() => {
        const modalElement = document.querySelector('.post-modal');
        console.log('模态框DOM元素是否存在:', !!modalElement);
        
        if (!modalElement && retryCount < 5) { // 最多尝试5次
          // 如果DOM元素不存在，延迟后重试
          setTimeout(() => {
            this.showModalWithRetry(retryCount + 1);
          }, 300 * (retryCount + 1)); // 递增延迟时间
          
          // 如果是最后几次尝试，尝试更激进的手段
          if (retryCount >= 2) {
            // 触发视图强制更新
            this.$forceUpdate();
            // 模拟用户点击，可能会触发某些事件处理
            document.dispatchEvent(new Event('click'));
            // 尝试改变URL而不触发路由变化，可能会刷新某些观察者
            history.replaceState(null, '', window.location.href);
          }
        } else if (!modalElement) {
          // 如果多次尝试后仍然失败，记录错误
          console.error('在多次尝试后仍然无法显示模态框');
          alert('打开帖子详情失败，请刷新页面重试');
        } else {
          // 模态框显示成功，重置滚动位置
          const modalBody = document.querySelector('.post-modal-body');
          if (modalBody) {
            modalBody.scrollTop = 0;
          }
          
          console.log('模态框显示成功！');
          
          // 如果用户已登录，检查是否关注了作者
          if (this.currentUser && this.currentPost && this.currentPost.author_id !== this.currentUser.id) {
            this.checkPostAuthorFollowStatus(this.currentPost.author_id);
          }
        }
      });
    },
    
    // 检查特定帖子作者的关注状态
    async checkPostAuthorFollowStatus(authorId) {
      if (!this.currentUser) return;
      
      try {
        const followResponse = await axios.get(API_ENDPOINTS.CHECK_FOLLOW_STATUS(authorId), {
          params: { follower_id: this.currentUser.id }
        });
        this.currentPost.isFollowing = followResponse.data.following;
      } catch (error) {
        console.error('检查关注状态失败:', error);
      }
    },
    
    // 初始URL检查 - 在created中调用
    initialUrlCheck() {
      // 解析URL哈希值和完整路径
      const hash = window.location.hash;
      const fullUrl = window.location.href;
      
      console.log('初始检查 - 当前URL:', fullUrl);
      console.log('初始检查 - 当前哈希值:', hash);
      
      // 尝试多种可能的URL格式匹配
      let match = null;
      
      // 专门匹配 http://localhost:8080/community#/community/post/8 这种最常见的格式
      if (fullUrl.includes('/community#/community/post/')) {
        match = fullUrl.match(/\/community#\/community\/post\/(\d+)/);
      }
      
      // 1. 匹配形如 #/community/post/123 的哈希路径
      if (!match) {
        match = hash.match(/#\/community\/post\/(\d+)/);
      }
      
      // 2. 如果上面没匹配到，尝试匹配 /community/post/123
      if (!match) {
        match = fullUrl.match(/\/community\/post\/(\d+)/);
      }
      
      // 3. 通用匹配 - 提取任何位置的post后面跟着的数字
      if (!match && hash.includes('post/')) {
        match = hash.match(/post\/(\d+)/);
      }
      
      // 4. 最后尝试提取URL中任何位置的数字作为帖子ID
      if (!match && (fullUrl.includes('post=') || hash.includes('post='))) {
        const postParam = new URLSearchParams(hash.replace('#', '?')).get('post') || 
                        new URLSearchParams(window.location.search).get('post');
        if (postParam) {
          match = [null, postParam];
        }
      }
      
      if (match && match[1]) {
        const postId = parseInt(match[1]);
        console.log(`初始检查 - 检测到URL中包含帖子ID: ${postId}，准备加载帖子详情`);
        
        this.isPostDetailLoaded = true; // 标记正在加载帖子详情
        
        // 检查用户是否已登录
        const isLoggedIn = localStorage.getItem('user') !== null;
        if (!isLoggedIn) {
          console.log('用户未登录，将在登录后再加载帖子详情');
          
          // 将帖子ID存储到localStorage，以便登录后加载
          localStorage.setItem('pending_post_id', postId.toString());
        } else {
          // 延迟一点时间再加载帖子，确保组件已完全初始化
          setTimeout(() => {
            console.log(`初始检查 - 开始加载帖子ID: ${postId}`);
            this.loadPostFromUrl(postId);
          }, 500);
        }
      } else {
        // 检查是否有待处理的帖子ID（从登录后跳转回来）
        const pendingPostId = localStorage.getItem('pending_post_id');
        if (pendingPostId) {
          console.log(`检测到待处理的帖子ID: ${pendingPostId}`);
          
          // 清除待处理的帖子ID
          localStorage.removeItem('pending_post_id');
          
          // 加载帖子详情
          this.isPostDetailLoaded = true;
          setTimeout(() => {
            console.log(`加载待处理的帖子ID: ${pendingPostId}`);
            this.loadPostFromUrl(parseInt(pendingPostId));
          }, 500);
        }
      }
      
      this.isInitialCheckDone = true;
    },
  }
};
</script>

<style scoped>
/* 恢复社区页面的原始样式 */
.community-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

h2 {
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

.dark-theme h2 {
  color: #e0e0e0;
}

.posts-filter {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  background: white;
  border-radius: 8px;
  padding: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.dark-theme .posts-filter {
  background: #1e1e24;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

.filter-item {
  padding: 8px 15px;
  margin-right: 10px;
  border-radius: 20px;
  font-size: 14px;
  color: #555;
  cursor: pointer;
  transition: all 0.3s;
}

.dark-theme .filter-item {
  color: #aaa;
}

.filter-item:hover, .filter-item.active {
  background: #f0f0f7;
  color: #4f46e5;
}

.dark-theme .filter-item:hover, 
.dark-theme .filter-item.active {
  background: #2a2a35;
  color: #818cf8;
}

.filter-item.active {
  font-weight: 500;
}

.new-post-btn {
  margin-left: auto;
  background: #4f46e5;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.3s;
}

.dark-theme .new-post-btn {
  background: #6366f1;
}

.new-post-btn:hover {
  background: #4338ca;
}

.dark-theme .new-post-btn:hover {
  background: #5157eb;
}

.posts-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.post-item {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
  padding: 20px;
  height: 500px;
  display: flex;
  flex-direction: column;
}

.dark-theme .post-item {
  background: #1e1e24;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
}

.post-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
}

.dark-theme .post-item:hover {
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.4);
}

.post-content {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 0;
  font-size: 16px;
  line-height: 1.7;
  color: #333;
}

.dark-theme .post-content {
  color: #e0e0e0;
}

.post-header {
  flex: 0 0 auto;
  height: 70px; /* 从原来的60px增加到70px */
  margin-bottom: 10px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.dark-theme .post-header {
  border-bottom: 1px solid #2a2a35;
}

.post-title {
  margin: 0;
  padding-bottom: 15px; /* 使用padding替代margin增加标题底部间距 */
  font-size: 18px;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.4;
}

.dark-theme .post-title {
  color: #e0e0e0;
}

.post-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
  color: #6b7280;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.dark-theme .post-meta {
  color: #9ca3af;
}

.post-text {
  flex: 0 0 auto;
  height: 80px;
  margin-bottom: 15px;
  line-height: 1.5;
  color: #444;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
}

.dark-theme .post-text {
  color: #d1d5db;
}

.post-preview {
  flex: 1 1 auto;
  margin-bottom: 15px;
  position: relative;
  border-radius: 8px;
  overflow: hidden;
  height: 200px; /* 设置固定高度，与无乐谱内容占位符保持一致 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.music-preview {
  width: 100%;
  max-height: 100%;
  object-fit: contain;
  border-radius: 8px;
  background-color: #f8f9fa;
  padding: 10px;
}

.play-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(67, 97, 238, 0.9);
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 20px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
  transition: all 0.2s ease;
}

.play-btn:disabled,
.play-button:disabled {
  background: rgba(167, 177, 218, 0.9);
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.play-btn:hover:not(:disabled) {
  background: rgba(67, 97, 238, 1);
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

/* 播放按钮样式 */
.play-button {
  background: #4361ee;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  width: 80%;
  max-width: 200px;
  text-align: center;
  box-shadow: 0 2px 5px rgba(67, 97, 238, 0.25);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.play-button i {
  font-size: 14px;
  line-height: 1;
  margin-right: 4px;
}

.play-button span {
  line-height: 1;
  margin-left: 4px;
}

.dark-theme .play-button {
  background: #6366f1;
}

.play-button:hover:not(:disabled) {
  background: #3a56e8;
  transform: translateY(-1px);
  box-shadow: 0 4px 10px rgba(67, 97, 238, 0.3);
}

.dark-theme .play-button:hover:not(:disabled) {
  background: #5157eb;
  box-shadow: 0 4px 10px rgba(99, 102, 241, 0.3);
}

/* 音乐标题样式 */
.music-title {
  font-size: 15px;
  font-weight: 500;
  color: #444;
  margin-bottom: 5px;
}

/* 移除不需要的样式 */
.progress-bar,
.music-controls {
  display: none;
}

.post-actions {
  flex: 0 0 auto;
  height: 50px;
  display: flex;
  gap: 20px;
  margin-top: auto;
  padding: 10px 0;
  border-top: 1px solid #eee;
  align-items: center;
}

.dark-theme .post-actions {
  border-top: 1px solid #2a2a35;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #6b7280;
  font-size: 14px;
  cursor: pointer;
  transition: color 0.2s;
  padding: 5px 10px;
  border-radius: 6px;
}

.dark-theme .action-item {
  color: #9ca3af;
}

.action-item:hover {
  color: #4f46e5;
  background: #f5f5ff;
}

.dark-theme .action-item:hover {
  color: #818cf8;
  background: #2a2a35;
}

.icon-heart,
.icon-comment,
.icon-share {
  font-size: 16px;
  line-height: 1;
}

/* 确保帖子中没有图片时的布局保持一致 */
.post-item:not(:has(.post-preview)) .post-text {
  flex: 1 1 auto;
}

.post-preview-placeholder {
  flex: 1 1 auto;
  height: 220px; /* 固定高度与乐谱图片一致 */
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f9fa;
  border-radius: 8px;
  margin-bottom: 15px;
  color: #aaa;
  font-style: italic;
}

.dark-theme .post-preview-placeholder {
  background-color: #252530;
  color: #666;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .post-item {
    height: 450px;
  }
  
  .post-header {
    height: 60px; /* 从50px调整为60px，为移动端提供足够空间 */
  }
  
  .post-text {
    height: 60px;
    -webkit-line-clamp: 2;
  }
  
  .post-preview, .post-preview-placeholder {
    height: 150px;
  }
  
  .post-actions {
    height: 45px;
    gap: 15px;
    padding: 8px 0;
  }
}

/* 恢复原始样式 - 帖子详情和评论区 */
.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.comment-header strong {
  font-size: 15px;
  font-weight: 600;
  color: #333;
}

.dark-theme .comment-header strong {
  color: #e0e0e0;
}

.comment-date {
  color: #888;
  font-size: 0.8rem;
}

.dark-theme .comment-date {
  color: #9ca3af;
}

.comment-content {
  color: #333;
  line-height: 1.6;
  font-size: 15px;
  padding: 8px 12px;
  background: #f9f9f9;
  border-radius: 8px;
  margin-top: 5px;
}

.dark-theme .comment-content {
  color: #e0e0e0;
  background: #2a2a35;
  border: 1px solid #3a3a45;
}

.no-comments {
  text-align: center;
  padding: 20px;
  color: #888;
  font-style: italic;
  background: #f9f9f9;
  border-radius: 8px;
  margin: 10px 0;
}

.dark-theme .no-comments {
  color: #9ca3af;
  background: #252530;
  border: 1px solid #2a2a35;
}

.add-comment {
  position: sticky;
  bottom: 0;
  background: #ffffff;
  padding-top: 10px;
  margin-top: 10px;
  z-index: 5;
}

.dark-theme .add-comment {
  background: #1e1e24;
}

.comment-input-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
  background: #f9f9f9;
  border: 1px solid #eaeaea;
  padding: 15px;
  border-radius: 8px;
}

.dark-theme .comment-input-container {
  background: #252530;
  border: 1px solid #2a2a35;
}

.comment-input {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  resize: vertical;
  min-height: 80px;
  font-family: inherit;
  font-size: 14px;
  margin-bottom: 10px;
  background: #ffffff;
}

.dark-theme .comment-input {
  background-color: #2a2a35;
  border: 1px solid #3a3a45;
  color: #e0e0e0;
}

.btn.primary {
  background: #4f46e5;
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-weight: 500;
  transition: all 0.3s ease;
  align-self: flex-end;
  font-size: 14px;
  float: right;
}

.dark-theme .btn.primary {
  background: #6366f1;
}

.btn.primary:hover {
  background: #4338ca;
  transform: translateY(-2px);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.dark-theme .btn.primary:hover {
  background: #5157eb;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
}

/* 发布新帖子表单样式 */
.form-group {
  margin-bottom: 25px;
}

.form-group label {
  display: block;
  margin-bottom: 10px;
  font-weight: 500;
  color: #444;
  font-size: 16px;
}

.dark-theme .form-group label {
  color: #e0e0e0;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-family: inherit;
  font-size: 15px;
  color: #333;
}

.dark-theme .form-group input,
.dark-theme .form-group textarea {
  color: #e0e0e0;
  background: #252530;
  border: 1px solid #3a3a45;
}

.text-count {
  text-align: right;
  color: #888;
  margin-top: 5px;
  font-size: 14px;
}

.dark-theme .text-count {
  color: #9ca3af;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 15px;
  margin-top: 30px;
}

.cancel-btn, .submit-btn {
  padding: 12px 25px;
  border-radius: 8px;
  font-size: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.cancel-btn {
  background: #f5f5f5;
  color: #555;
  border: none;
}

.cancel-btn:hover {
  background: #ebebeb;
}

.submit-btn {
  background: #4f46e5;
  color: white;
  border: none;
  padding: 12px 25px;
  border-radius: 8px;
  font-size: 15px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.submit-btn:not(:disabled):hover {
  background: #4338ca;
  transform: translateY(-2px);
  box-shadow: 0 2px 10px rgba(79, 70, 229, 0.2);
}

.submit-btn:disabled {
  background: #a5a5a5;
  cursor: not-allowed;
  opacity: 0.7;
  color: #ffffff;
}

/* 乐谱上传相关样式 */
.score-upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 30px;
  background: #f9f9f9;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.dark-theme .score-upload-area {
  border: 2px dashed #3a3a45;
  background: #252530;
}

.score-upload-area:hover {
  border-color: #4f46e5;
  background: #f5f5ff;
}

.dark-theme .score-upload-area:hover {
  border-color: #6366f1;
  background: #2a2a35;
}

.upload-placeholder {
  text-align: center;
}

.upload-icon {
  font-size: 32px;
  color: #6b7280;
  margin-bottom: 10px;
  display: block;
}

.dark-theme .upload-icon {
  color: #9ca3af;
}

.upload-hint {
  color: #888;
  font-size: 14px;
  margin-top: 5px;
}

.dark-theme .upload-hint {
  color: #9ca3af;
}

.preview-container {
  width: 100%;
  position: relative;
}

.preview-image {
  width: 100%;
  max-height: 300px;
  object-fit: contain;
  border-radius: 5px;
  background: #f9f9f9;
}

.dark-theme .preview-image {
  background: #252530;
  border: 1px solid #2a2a35;
}

.remove-preview {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  width: 25px;
  height: 25px;
  border-radius: 50%;
  font-size: 16px;
  line-height: 1;
  cursor: pointer;
  transition: all 0.2s ease;
}

.remove-preview:hover {
  background: rgba(0, 0, 0, 0.7);
  transform: scale(1.1);
}

.score-upload-area.has-preview {
  border: none;
  padding: 0;
  background: none;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .post-item {
    height: 450px;
  }
  
  .post-header {
    height: 60px; /* 从50px调整为60px，为移动端提供足够空间 */
  }
  
  .post-text {
    height: 60px;
    -webkit-line-clamp: 2;
  }
  
  .post-preview, .post-preview-placeholder {
    height: 150px;
  }
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px 0;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #4f46e5;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 10px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.dark-theme .loading-spinner {
  border: 4px solid #333;
  border-top: 4px solid #6366f1;
}

/* 错误消息样式 */
.error-message {
  background-color: #fee2e2;
  color: #b91c1c;
  padding: 12px 16px;
  border-radius: 8px;
  margin: 20px 0;
  text-align: center;
}

.dark-theme .error-message {
  background-color: #7f1d1d;
  color: #fecaca;
}

/* 空帖子提示样式 */
.no-posts {
  background-color: #f9fafb;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
  margin: 20px 0;
  color: #6b7280;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
}

.dark-theme .no-posts {
  background-color: #1e1e24;
  color: #9ca3af;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
}

/* 点赞文本样式 */
.liked-text {
  color: #ef4444;
  font-weight: bold;
}

/* 鼠标悬停效果 */
.action-item:hover .icon-heart {
  transform: scale(1.1);
}

.action-item:hover .icon-heart.liked {
  transform: scale(1.3);
}

.follow-btn {
  background: #4f46e5;
  color: white;
  border: none;
  padding: 8px 15px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: background 0.3s;
}

.dark-theme .follow-btn {
  background: #6366f1;
}

.follow-btn:hover {
  background: #4338ca;
}

.dark-theme .follow-btn:hover {
  background: #5157eb;
}

.following {
  background: #6366f1;
  color: white;
}

.dark-theme .following {
  background: #4f46e5;
}
</style>

<style>
/* 使用非scoped样式，确保能作用于teleport到body的元素 */

/* 帖子详情模态框 - 美化版本 */
.post-modal {
  position: fixed;
  z-index: 100000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: rgba(0, 0, 0, 0.75);
  backdrop-filter: blur(3px);
  -webkit-backdrop-filter: blur(3px);
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  animation: modalBackgroundFadeIn 0.3s ease;
}

.post-modal-content {
  background-color: #ffffff;
  width: 95%;
  max-width: 1200px;
  height: 90vh;
  max-height: 90vh;
  border-radius: 16px;
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.25), 0 5px 15px rgba(0, 0, 0, 0.15);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  animation: modalContentSlideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.dark-theme .post-modal-content {
  background-color: #1e1e24;
  border: 1px solid rgba(255, 255, 255, 0.05);
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.5), 0 5px 15px rgba(0, 0, 0, 0.3);
}

.post-modal-header {
  padding: 20px 25px;
  background: #fcfcfc;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.02);
  position: relative;
  z-index: 1;
}

.dark-theme .post-modal-header {
  background: #252530;
  border-bottom: 1px solid #2a2a35;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.post-modal-header h3 {
  margin: 0;
  font-size: 22px;
  color: #1a1a1a;
  font-weight: 600;
  letter-spacing: -0.01em;
  position: relative;
  padding-left: 3px;
}

.dark-theme .post-modal-header h3 {
  color: #e0e0e0;
}

.post-modal-close {
  background: rgba(0, 0, 0, 0.05);
  border: none;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  font-size: 24px;
  line-height: 34px;
  color: #555;
  cursor: pointer;
  outline: none;
  padding: 0;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.dark-theme .post-modal-close {
  background: rgba(255, 255, 255, 0.1);
  color: #aaa;
}

.post-modal-close:hover {
  background: rgba(0, 0, 0, 0.1);
  color: #000;
  transform: rotate(90deg);
}

.dark-theme .post-modal-close:hover {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
}

.post-modal-body {
  padding: 30px 35px;
  overflow-y: auto !important;
  -webkit-overflow-scrolling: touch;
  flex: 1 1 auto;
  background: #fff;
  scrollbar-width: thin;
  scrollbar-color: #d0d0d0 #f5f5f5;
  max-height: calc(90vh - 70px);
  position: relative;
}

.dark-theme .post-modal-body {
  background: #1e1e24;
  scrollbar-color: #4a4a55 #252530;
  color: #ffffff;
}

.post-modal-body::-webkit-scrollbar {
  width: 8px;
}

.post-modal-body::-webkit-scrollbar-track {
  background: #f5f5f5;
}

.dark-theme .post-modal-body::-webkit-scrollbar-track {
  background: #252530;
}

.post-modal-body::-webkit-scrollbar-thumb {
  background-color: #d0d0d0;
  border-radius: 8px;
  border: 2px solid #f5f5f5;
}

.dark-theme .post-modal-body::-webkit-scrollbar-thumb {
  background-color: #4a4a55;
  border: 2px solid #252530;
}

/* 发布新帖子模态框 - 美化版本 */
.new-post-modal-portal {
  position: fixed;
  z-index: 100000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: rgba(0, 0, 0, 0.85);
  backdrop-filter: blur(3px);
  -webkit-backdrop-filter: blur(3px);
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  animation: modalBackgroundFadeIn 0.3s ease;
}

.new-post-modal-content {
  background-color: #ffffff;
  width: 95%;
  max-width: 1200px;
  height: 90vh;
  max-height: 90vh;
  border-radius: 16px;
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.25), 0 5px 15px rgba(0, 0, 0, 0.15);
  padding: 30px 35px;
  display: flex;
  flex-direction: column;
  overflow-y: auto !important;
  -webkit-overflow-scrolling: touch;
  position: relative;
  animation: modalContentSlideUp 0.4s cubic-bezier(0.16, 1, 0.3, 1);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.dark-theme .new-post-modal-content {
  background-color: #1e1e24;
  border: 1px solid rgba(255, 255, 255, 0.05);
  box-shadow: 0 15px 40px rgba(0, 0, 0, 0.5), 0 5px 15px rgba(0, 0, 0, 0.3);
}

.new-post-modal-close {
  position: absolute;
  right: 25px;
  top: 20px;
  background: rgba(0, 0, 0, 0.05);
  border: none;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  font-size: 24px;
  line-height: 34px;
  color: #555;
  cursor: pointer;
  outline: none;
  padding: 0;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.dark-theme .new-post-modal-close {
  background: rgba(255, 255, 255, 0.1);
  color: #aaa;
}

.new-post-modal-close:hover {
  background: rgba(0, 0, 0, 0.1);
  color: #000;
  transform: rotate(90deg);
}

.dark-theme .new-post-modal-close:hover {
  background: rgba(255, 255, 255, 0.2);
  color: #fff;
}

.new-post-modal-header {
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
}

.dark-theme .new-post-modal-header {
  border-bottom: 1px solid #2a2a35;
}

.new-post-modal-header h3 {
  margin: 0;
  font-size: 22px;
  color: #1a1a1a;
  font-weight: 600;
  letter-spacing: -0.01em;
}

.dark-theme .new-post-modal-header h3 {
  color: #e0e0e0;
}

/* 确保模态框中的表单元素样式正确 */
.post-modal .comment-input,
.new-post-modal-portal .form-group input,
.new-post-modal-portal .form-group textarea {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-family: inherit;
  font-size: 14px;
  background-color: #fff;
}

.dark-theme .post-modal .comment-input,
.dark-theme .new-post-modal-portal .form-group input,
.dark-theme .new-post-modal-portal .form-group textarea {
  background-color: #252530;
  border-color: #3a3a45;
  color: #ffffff;
}

.post-modal .comment-input:focus,
.new-post-modal-portal .form-group input:focus,
.new-post-modal-portal .form-group textarea:focus {
  outline: none;
  border-color: #4f46e5;
  box-shadow: 0 0 0 2px rgba(79, 70, 229, 0.2);
}

.dark-theme .post-modal .comment-input:focus,
.dark-theme .new-post-modal-portal .form-group input:focus,
.dark-theme .new-post-modal-portal .form-group textarea:focus {
  border-color: #6366f1;
  box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.2);
}

.post-modal .btn.primary,
.new-post-modal-portal .submit-btn {
  background: #4f46e5;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 8px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.dark-theme .post-modal .btn.primary,
.dark-theme .new-post-modal-portal .submit-btn {
  background: #6366f1;
}

.post-modal .btn.primary:hover,
.new-post-modal-portal .submit-btn:not(:disabled):hover {
  background: #4338ca;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(79, 70, 229, 0.2);
}

.dark-theme .post-modal .btn.primary:hover,
.dark-theme .new-post-modal-portal .submit-btn:not(:disabled):hover {
  background: #5157eb;
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
}

/* 增强动画效果 */
@keyframes modalBackgroundFadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes modalContentSlideUp {
  from {
    opacity: 0;
    transform: translateY(30px) scale(0.97);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

/* 移动设备适配 */
@media (max-width: 768px) {
  .post-modal-content,
  .new-post-modal-content {
    width: 100%;
    height: 100%;
    max-height: 100%;
    border-radius: 0;
    border: none;
  }
  
  .post-modal-header {
    padding: 15px 20px;
  }
  
  .post-modal-body {
    padding: 20px;
  }
  
  .new-post-modal-content {
    padding: 20px;
  }
  
  .post-modal-close,
  .new-post-modal-close {
    right: 15px;
    top: 10px;
    width: 32px;
    height: 32px;
  }
}

/* 添加额外的滚动修复 */
.post-modal,
.new-post-modal-portal {
  position: fixed;
  z-index: 100000;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: rgba(0, 0, 0, 0.75);
  backdrop-filter: blur(3px);
  -webkit-backdrop-filter: blur(3px);
  display: flex;
  justify-content: center;
  align-items: center;
  box-sizing: border-box;
  animation: modalBackgroundFadeIn 0.3s ease;
  /* 确保模态框本身不滚动 */
}

/* 添加触摸设备专用的滚动修复 */
@supports (-webkit-touch-callout: none) {
  /* iOS Safari 专用样式 */
  .post-modal-body,
  .new-post-modal-content {
    -webkit-overflow-scrolling: touch !important;
  }
}

/* 添加明确的模态框内容样式，确保滚动正常 */
.post-detail {
  display: flex;
  flex-direction: column;
  gap: 20px;
  /* 不限制高度，让内容自然流动 */
  height: auto;
  min-height: 0;
}

/* 确保模态框中的评论区可以正常滚动 */
.post-modal .comments-list {
  margin-top: 15px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  max-height: none !important; /* 移除高度限制 */
  overflow-y: visible !important; /* 不使用内部滚动 */
  padding-right: 15px;
}

/* 确保模态框内部所有可滚动区域的触摸滚动正常工作 */
.post-modal-body *,
.new-post-modal-content * {
  touch-action: pan-y; /* 允许垂直触摸滚动 */
}

/* 解决在某些浏览器中模态框内容滚动问题 */
.post-modal-content {
  overflow: hidden !important; /* 确保外层不滚动 */
}

.post-modal-body {
  overscroll-behavior: contain; /* 防止滚动链接到外层 */
}

/* 在移动设备上进一步优化滚动 */
@media (max-width: 768px) {
  .post-modal-body,
  .new-post-modal-content {
    max-height: calc(100vh - 60px) !important;
    padding-bottom: 50px !important; /* 确保有足够的底部空间 */
  }
}

/* 修复可能的内容溢出问题 */
.comment-content,
.post-content {
  word-break: break-word; /* 允许长单词换行 */
  overflow-wrap: break-word;
}

.music-cover {
  width: 120px;
  height: 120px;
  object-fit: contain;
  border-radius: 8px;
  background-color: #f8f9fa;
  padding: 5px;
  border: 1px solid #eaeaea;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.music-cover:hover {
  transform: scale(1.05);
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
}

.image-hint {
  font-size: 12px;
  color: #6b7280;
  text-align: center;
  margin-top: 5px;
  font-style: italic;
}

/* 查看大图弹窗样式 */
.large-image-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.9);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 200000;
  cursor: zoom-out;
  animation: fadeIn 0.3s ease;
}

.large-image-container {
  position: relative;
  max-width: 90%;
  max-height: 90%;
}

.large-image {
  max-width: 100%;
  max-height: 90vh;
  object-fit: contain;
  border-radius: 4px;
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.3);
}

.close-large-image {
  position: absolute;
  top: -40px;
  right: -40px;
  width: 36px;
  height: 36px;
  background: rgba(255, 255, 255, 0.2);
  border: none;
  border-radius: 50%;
  color: white;
  font-size: 24px;
  line-height: 32px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.close-large-image:hover {
  background: rgba(255, 255, 255, 0.4);
  transform: rotate(90deg);
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

/* 优化音乐播放器布局 */
.music-player {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  padding: 15px;
  background: #f9f9fa;
  border-radius: 10px;
  margin: 10px 0;
}

.dark-theme .music-player {
  background: #252530;
  border: 1px solid #2a2a35;
}

.score-image-container {
  text-align: center;
  width: 100%;
}

.music-cover {
  width: 100%;
  max-width: 400px;
  height: auto;
  object-fit: contain;
  border-radius: 8px;
  background-color: #f8f9fa;
  padding: 5px;
  border: 1px solid #eaeaea;
  cursor: pointer;
  transition: transform 0.2s ease;
  display: block;
  margin: 0 auto 10px;
}

.image-hint {
  font-size: 12px;
  color: #6b7280;
  text-align: center;
  margin-top: 5px;
  font-style: italic;
}

.play-button {
  background: #4361ee;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 6px;
  font-size: 15px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  width: 80%;
  max-width: 200px;
  text-align: center;
  box-shadow: 0 2px 5px rgba(67, 97, 238, 0.25);
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.play-button i {
  font-size: 16px;
  margin-right: 8px;
}

.play-button span {
  margin-left: 8px;
}

.dark-theme .play-button {
  background: #6366f1;
}

.play-button:hover:not(:disabled) {
  background: #3a56e8;
  transform: translateY(-1px);
  box-shadow: 0 4px 10px rgba(67, 97, 238, 0.3);
}

.dark-theme .play-button:hover:not(:disabled) {
  background: #5157eb;
  box-shadow: 0 4px 10px rgba(99, 102, 241, 0.3);
}

/* 音频控制面板样式 */
.audio-control-panel {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background: rgba(255, 255, 255, 0.95);
  padding: 15px;
  border-top: 1px solid #eaeaea;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 100000; /* 确保显示在最上层 */
  animation: slideUp 0.3s ease;
}

.dark-theme .audio-control-panel {
  background: rgba(30, 30, 35, 0.95);
  border-top: 1px solid #2a2a35;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.3);
}

.progress-container {
  margin-bottom: 10px;
}

.progress-bar-bg {
  width: 100%;
  height: 6px;
  background: #e0e0e0;
  border-radius: 3px;
  overflow: hidden;
  cursor: pointer;
}

.dark-theme .progress-bar-bg {
  background: #3a3a45;
}

.progress-bar-fill {
  height: 100%;
  background: #4f46e5;
  border-radius: 3px;
  transition: width 0.1s linear;
}

.dark-theme .progress-bar-fill {
  background: #6366f1;
}

.time-display {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #666;
  margin-top: 5px;
}

.dark-theme .time-display {
  color: #aaa;
}

.controls {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.control-btn {
  background: #4f46e5;
  color: white;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: none;
  font-size: 16px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.dark-theme .control-btn {
  background: #6366f1;
}

.control-btn:hover {
  background: #4338ca;
  transform: scale(1.05);
}

.dark-theme .control-btn:hover {
  background: #5157eb;
}

.volume-control, .speed-control {
  display: flex;
  align-items: center;
  gap: 10px;
}

.dark-theme .volume-control, 
.dark-theme .speed-control {
  color: #ddd;
}

.volume-control input, .speed-control select {
  padding: 5px;
  border-radius: 4px;
  border: 1px solid #ddd;
}

.dark-theme .volume-control input, 
.dark-theme .speed-control select {
  background: #2a2a35;
  border-color: #3a3a45;
  color: #ddd;
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

@media (max-width: 768px) {
  .audio-control-panel {
    padding: 10px;
  }
  
  .controls {
    flex-wrap: wrap;
    gap: 10px;
  }
}

/* 上传进度条样式 */
.upload-progress-container {
  width: 100%;
  height: 10px;
  background: #f0f0f0;
  border-radius: 5px;
  overflow: hidden;
  margin-top: 10px;
}

.upload-progress-bar {
  height: 100%;
  background: #4f46e5;
  border-radius: 5px;
  transition: width 0.3s ease;
}

/* 加载旋转动画 */
.loading-spinner {
  display: inline-block;
  width: 14px;
  height: 14px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: #fff;
  animation: spin 1s ease-in-out infinite;
  margin-right: 6px;
  vertical-align: middle;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}
</style> 

<style>
/* 帖子详情页中作者名称和关注按钮布局 */
.author-name-follow {
  display: flex;
  align-items: center;
  gap: 10px;
}

.author-name-follow h4 {
  margin: 0;
}

/* 帖子详情页的点赞按钮 */
.post-detail-actions {
  margin: 20px 0;
  display: flex;
  justify-content: center;
}

.action-btn-group {
  display: flex;
  gap: 15px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 8px 15px;
  border-radius: 20px;
  border: 1px solid #eaeaea;
  background: white;
  cursor: pointer;
  transition: all 0.2s ease;
}

.dark-theme .action-btn {
  background: #252530;
  border: 1px solid #3a3a45;
  color: #e0e0e0;
}

.action-btn:hover {
  background: #f5f5ff;
  transform: translateY(-2px);
}

.dark-theme .action-btn:hover {
  background: #2a2a35;
}

.liked-btn {
  background: #fff5f5;
  border-color: #fee2e2;
}

.dark-theme .liked-btn {
  background: #3b1d1d;
  border-color: #7f1d1d;
}
</style> 

<style>
/* 点赞图标样式 */
.icon-heart {
  position: relative;
  font-size: 18px;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

/* 未点赞状态 */
.icon-heart:not(.liked) {
  opacity: 0.7;
  filter: grayscale(30%);
}

/* 已点赞状态 */
.icon-heart.liked {
  color: #ff3b30;
  font-weight: bold;
  transform: scale(1.2);
  text-shadow: 0 0 5px rgba(255, 59, 48, 0.3);
}

.liked-text {
  color: #ff3b30;
  font-weight: bold;
}

/* 点赞按钮动画 */
@keyframes heartPulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.4); }
  100% { transform: scale(1.2); }
}

.heartPulse {
  animation: heartPulse 0.4s ease-in-out;
}

/* 上传状态样式 */
.upload-status {
  background: #f9f9fb;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 20px;
  text-align: center;
}

.dark-theme .upload-status {
  background: #2a2a35;
}

.progress-container {
  height: 8px;
  background: #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 10px;
}

.progress-bar {
  height: 100%;
  background: linear-gradient(to right, #4f46e5, #818cf8);
  border-radius: 4px;
  transition: width 0.3s ease;
}

.progress-text {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.dark-theme .progress-text {
  color: #aaa;
}

.upload-message {
  font-size: 12px;
  color: #888;
}

.dark-theme .upload-message {
  color: #999;
}

/* 禁用状态 */
.form-group.disabled {
  opacity: 0.7;
  pointer-events: none;
}
</style> 

<style>
/* 调试信息样式 */
.debug-info {
  color: #888;
  font-size: 12px;
  margin-top: 5px;
}
</style> 

